import pandas as pd
import numpy as np
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt

# 1. 数据清洗和预处理
df = pd.read_csv('./data/数据分析/nba2k-full.csv')
df = df.drop(['height', 'weight','b_day','draft_peak','draft_round','version'], axis=1)  # 排除height和weight字段
df = df.dropna()  # 清洗缺失数据  

# 数据预处理  
# 对分类变量进行编码（例如：球队、位置、国家等）  
categorical_columns = ['team', 'position', 'country', 'college']
df_encoded = pd.get_dummies(df, columns=categorical_columns)

# 分离特征和目标变量  
X = df_encoded.drop(['full_name', 'rating', 'salary'], axis=1)
y_rating = df_encoded['rating']
y_salary = df_encoded['salary']

# 数据分析  
# 1. 球员平均评分最高  
top_rated_players = df.groupby('full_name')['rating'].mean().sort_values(ascending=False).head(5)
print("球员平均评分最高：")
print(top_rated_players)

# 2. NBA2K中薪水最高的球员  
highest_paid_player = df.loc[df['salary'].idxmax()]
print("\nNBA2K中薪水最高的球员：")
print(highest_paid_player[['full_name', 'salary']])

# 3. 哪些大学为NBA输送了最多的球员  
top_colleges = df['college'].value_counts().head(5)
print("\n为NBA输送球员最多的大学：")
print(top_colleges)

# 模型构建与预测  
# 划分训练集和测试集  
X_train_rating, X_test_rating, y_train_rating, y_test_rating = train_test_split(X, y_rating, test_size=0.2, random_state=42)
X_train_salary, X_test_salary, y_train_salary, y_test_salary = train_test_split(X, y_salary, test_size=0.2, random_state=42)

# 使用不同的回归模型进行训练和预测  
models = {'Linear Regression': LinearRegression(), 'Ridge Regression': Ridge(), 'Lasso Regression': Lasso()}

for name, model in models.items():
    # 训练评分预测模型  
    model.fit(X_train_rating, y_train_rating)
    y_pred_rating = model.predict(X_test_rating)
    mse_rating = mean_squared_error(y_test_rating, y_pred_rating)
    print(f"\n{name} 评分预测 MSE: {mse_rating}")

    # 训练薪水预测模型  
    model.fit(X_train_salary, y_train_salary)
    y_pred_salary = model.predict(X_test_salary)
    mse_salary = mean_squared_error(y_test_salary, y_pred_salary)
    print(f"{name} 薪水预测 MSE: {mse_salary}")

# 由于没有提供下一版本的数据，我们将使用整个数据集进行预测，以展示预测过程  
# 假设我们有一个新的球员数据 new_player_data（此处用整个数据集代替）  
new_player_data = X

# 使用表现最好的模型进行预测（这里以Ridge Regression为例）  
best_model_rating = models['Ridge Regression']
best_model_rating.fit(X, y_rating)
predicted_ratings = best_model_rating.predict(new_player_data)
top_predicted_ratings = pd.Series(predicted_ratings).sort_values(ascending=False).head(5)
print("\n预测下一个版本的NBA2K中评分最高的球员（示例，实际需用新数据）：")
print(top_predicted_ratings)

best_model_salary = models['Ridge Regression']
best_model_salary.fit(X, y_salary)
predicted_salaries = best_model_salary.predict(new_player_data)
top_predicted_salaries = pd.Series(predicted_salaries).sort_values(ascending=False).head(5)
print("\n预测下一个版本的NBA2K中薪水最高的球员（示例，实际需用新数据）：")
print(top_predicted_salaries)

# 结果可视化（略，具体可视化方法取决于数据的特性和分析需求）  
# 例如，可以使用matplotlib绘制球员评分和薪水的分布图、回归模型的预测结果等。
# 可视化部分

# 1. 球员平均评分最高的条形图
top_rated_players_index = top_rated_players.index.tolist()
top_rated_players_values = top_rated_players.tolist()

plt.figure(figsize=(10, 6))
plt.bar(top_rated_players_index, top_rated_players_values, color='blue')
plt.title('Top 5 Highest Rated Players')
plt.xlabel('Player Name')
plt.ylabel('Average Rating')
plt.xticks(rotation=45)  # 旋转x轴标签以便于阅读
plt.tight_layout()
plt.show()

# 2. NBA2K中薪水最高的球员的条形图（这里只展示最高薪水球员）
plt.figure(figsize=(10, 6))
plt.bar(highest_paid_player['full_name'], highest_paid_player['salary'], color='green')
plt.title('Highest Paid Player in NBA2K')
plt.xlabel('Player Name')
plt.ylabel('Salary')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 3. 为NBA输送球员最多的大学的饼图
top_colleges_labels = top_colleges.index.tolist()
top_colleges_values = top_colleges.tolist()

plt.figure(figsize=(10, 6))
plt.pie(top_colleges_values, labels=top_colleges_labels, autopct='%1.1f%%', startangle=140)
plt.title('Top 5 Colleges Supplying NBA Players')
plt.axis('equal')  # 确保饼图是圆形的
plt.show()

# 假设top_colleges是一个Pandas Series，其中索引是大学名称，值是对应的球员数量
top_colleges_dict = top_colleges.to_dict()

# 创建词云
wordcloud = WordCloud(width=800, height=400, background_color='white', min_font_size=10)
wordcloud.generate_from_frequencies(top_colleges_dict)

# 显示词云图
plt.figure(figsize=(10, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')  # 不显示坐标轴
plt.title('Top Colleges Supplying NBA Players')
plt.show()

# 4. 预测评分与实际评分的散点图
plt.figure(figsize=(10, 6))
plt.scatter(y_test_rating, y_pred_rating, color='red', alpha=0.5)
plt.title('Predicted vs Actual Ratings')
plt.xlabel('Actual Rating')
plt.ylabel('Predicted Rating')
plt.show()

# 5. 预测薪水与实际薪水的散点图
plt.figure(figsize=(10, 6))
plt.scatter(y_test_salary, y_pred_salary, color='purple', alpha=0.5)
plt.title('Predicted vs Actual Salaries')
plt.xlabel('Actual Salary')
plt.ylabel('Predicted Salary')
plt.show()

# 6. 预测评分的直方图
plt.figure(figsize=(10, 6))
plt.hist(predicted_ratings, bins=30, color='blue', alpha=0.7)
plt.title('Distribution of Predicted Ratings')
plt.xlabel('Predicted Rating')
plt.ylabel('Frequency')
plt.show()

# 7. 预测薪水的直方图
plt.figure(figsize=(10, 6))
plt.hist(predicted_salaries, bins=30, color='green', alpha=0.7)
plt.title('Distribution of Predicted Salaries')
plt.xlabel('Predicted Salary')
plt.ylabel('Frequency')
plt.show()
